package com.fatan.xiaopacai.mvvm.viewmodel

import android.util.Log
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import com.fatan.xiaopacai.base.BaseViewModel
import com.fatan.xiaopacai.base.TAG
import com.fatan.xiaopacai.mvvm.model.PuKe
import com.fatan.xiaopacai.mvvm.model.allPuKe
import com.fatan.xiaopacai.mvvm.model.maxPuKeNum
import com.fatan.xiaopacai.mvvm.model.minPuKeNum
import com.fatan.xiaopacai.room.AppDataBase
import com.fatan.xiaopacai.room.randompuke.RandomPuKeEntity
import com.fatan.xiaopacai.util.JsonUtil

/**
 * @author: WangYeTong
 * @date: 2023/12/28 16:53
 * @remake:
 */
class RandomPuKeViewModel : BaseViewModel() {
    /**
     * 扑克牌数量
     */
    private val _puKeNum = mutableIntStateOf(3)
    val puKeNum: MutableIntState
        get() = _puKeNum

    /**
     * 随机扑克列表
     */
    private val _puKeRandomDataList = mutableStateOf<List<PuKe>>(listOf())
    val puKeRandomDataList: MutableState<List<PuKe>>
        get() = _puKeRandomDataList

    fun puKeAdd() {
        if (_puKeNum.intValue < maxPuKeNum) {
            _puKeNum.intValue++
        }
    }

    fun puKeMinus() {
        if (_puKeNum.intValue > minPuKeNum) {
            _puKeNum.intValue--
        }
    }

    /**
     * 获取随机扑克
     */
    fun getRandomDataList() {
        val tempList = mutableListOf<PuKe>()
        for (index in 0 until _puKeNum.intValue) {
            addRandomPuke(tempList)
        }
        _puKeRandomDataList.value = tempList
    }

    /**
     * 获取GridList的行数
     */
    fun getGridCount() = when (_puKeRandomDataList.value.size) {
        0, 1, 2, 3 -> 1
        else -> 2
    }

    fun addRecord(data: List<PuKe>) = serverAwait {
        Log.i(TAG, "添加随机扑克到数据库:${JsonUtil.toJson(data)}")
        AppDataBase.database.randomPuKeDao().insertAll(RandomPuKeEntity(puKeList = data, timeMill = System.currentTimeMillis()))
    }

    private fun addRandomPuke(dataList: MutableList<PuKe>) {
        val puke = allPuKe.random()
        if (!dataList.contains(puke)) {
            dataList.add(puke)
        } else {
            addRandomPuke(dataList)
        }
    }

}